package excel.countryMedicine;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import po.MyObject;
import util.AbstractExl;
import util.Conts;
import util.DateGroup;
import util.ExlDate;
import util.UsualUtil;

public class MedicalOrg extends AbstractExl {
	private static final Logger LOG = Logger.getLogger(MedicalOrg.class);
	private static final String DATE_FORMAT_1 = "yyyy-MM-dd";
	private static final String DATE_FORMAT_2 = "yyyyMMdd";
	private static String fileName = "药品经营企业";
	private int startNum = 1;
	private int endNum = Conts.PAGE_MEDICAL_ORG;
	private static String filePath = Conts.HTM_ROOT_PATH+fileName+"/";
	private static String outputFolder = Conts.EXL_ROOT_PATH;
	private static String regex = "<tr>.*?"
			+"<td bgcolor=\"#eaeaea\" style=\"text-align:right\" width=17% nowrap=\"true\">证号</td>.*?"
			+"<td bgcolor=\"#eaeaea\" width=83%>(.*?)</td>.*?</tr>.*?"
			+"<tr>.*?"
			+"<td bgcolor=\"#ffffff\" style=\"text-align:right\" width=17% nowrap=\"true\">企业名称</td>.*?"
			+"<td bgcolor=\"#ffffff\" width=83%>(.*?)</td>.*?</tr>.*?"
			+"<tr>.*?"
			+"<td bgcolor=\"#eaeaea\" style=\"text-align:right\" width=17% nowrap=\"true\">注册地址</td>.*?"
			+"<td bgcolor=\"#eaeaea\" width=83%>(.*?)</td>.*?</tr>.*?"
			+"<tr>.*?"
			+"<td bgcolor=\"#ffffff\" style=\"text-align:right\" width=17% nowrap=\"true\">仓库地址</td>.*?"
			+"<td bgcolor=\"#ffffff\" width=83%>(.*?)</td>.*?</tr>.*?"
			+"<tr>.*?"
			+"<td bgcolor=\"#eaeaea\" style=\"text-align:right\" width=17% nowrap=\"true\">法定代表人</td>.*?"
			+"<td bgcolor=\"#eaeaea\" width=83%>(.*?)</td>.*?</tr>.*?"
			+"<tr>.*?"
			+"<td bgcolor=\"#ffffff\" style=\"text-align:right\" width=17% nowrap=\"true\">企业负责人</td>.*?"
			+"<td bgcolor=\"#ffffff\" width=83%>(.*?)</td>.*?</tr>.*?"
			+"<tr>.*?"
			+"<td bgcolor=\"#eaeaea\" style=\"text-align:right\" width=17% nowrap=\"true\">质量负责人</td>.*?"
			+"<td bgcolor=\"#eaeaea\" width=83%>(.*?)</td>.*?</tr>.*?"
			+"<tr>.*?"
			+"<td bgcolor=\"#ffffff\" style=\"text-align:right\" width=17% nowrap=\"true\">经营方式</td>.*?"
			+"<td bgcolor=\"#ffffff\" width=83%>(.*?)</td>.*?</tr>.*?"
			+"<tr>.*?"
			+"<td bgcolor=\"#eaeaea\" style=\"text-align:right\" width=17% nowrap=\"true\">经营范围</td>.*?"
			+"<td bgcolor=\"#eaeaea\" width=83%>(.*?)</td>.*?</tr>.*?"
			+"<tr>.*?"
			+"<td bgcolor=\"#ffffff\" style=\"text-align:right\" width=17% nowrap=\"true\">发证日期</td>.*?"
			+"<td bgcolor=\"#ffffff\" width=83%>(.*?)</td>.*?</tr>.*?"
			+"<tr>.*?"
			+"<td bgcolor=\"#eaeaea\" style=\"text-align:right\" width=17% nowrap=\"true\">有效期至</td>.*?"
			+"<td bgcolor=\"#eaeaea\" width=83%>(.*?)</td>.*?</tr>.*?"
			+"<tr>.*?"
			+"<td bgcolor=\"#ffffff\" style=\"text-align:right\" width=17% nowrap=\"true\">发证部门</td>.*?"
			+"<td bgcolor=\"#ffffff\" width=83%>(.*?)</td>.*?</tr>.*?"
			+"<tr>.*?"
			+"<td bgcolor=\"#eaeaea\" style=\"text-align:right\" width=17% nowrap=\"true\">备注</td>.*?"
			+"<td bgcolor=\"#eaeaea\" width=83%>(.*?)</td>.*?</tr>.*?"
			+"id is 【(.*?)】";

	private void writeExl(List<MyObject> list) {
		File folder = new File(outputFolder);
		if (!folder.exists()) folder.mkdirs();
		FileOutputStream fOut = null;
		try {
			Workbook workbook = new SXSSFWorkbook(2000);
			Sheet sheet = workbook.createSheet("Sheet1");
			Row row = null;
			fOut = new FileOutputStream(outputFolder+fileName+".xlsx");
				for (int i = 0; i < list.size(); i++) {
					row = sheet.createRow(i);
					row.createCell((short)0).setCellValue(list.get(i).getObj1().trim());
					row.createCell((short)1).setCellValue(list.get(i).getObj2().trim());
					row.createCell((short)2).setCellValue(list.get(i).getObj3().trim());
					row.createCell((short)3).setCellValue(list.get(i).getObj4().trim());
					row.createCell((short)4).setCellValue(list.get(i).getObj5().trim());
					row.createCell((short)5).setCellValue(list.get(i).getObj6().trim());
					row.createCell((short)6).setCellValue(list.get(i).getObj7().trim());
					row.createCell((short)7).setCellValue(list.get(i).getObj8().trim());
					row.createCell((short)8).setCellValue(list.get(i).getObj9().trim());
					row.createCell((short)9).setCellValue(list.get(i).getObj10().trim());
					row.createCell((short)10).setCellValue(list.get(i).getObj11().trim());
					row.createCell((short)11).setCellValue(list.get(i).getObj12().trim());
					row.createCell((short)12).setCellValue(list.get(i).getObj13().trim());
					row.createCell((short)13).setCellValue(list.get(i).getObj14());
					LOG.info("It had "+i+" rows");
				}
			workbook.write(fOut);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != fOut) {
				try {
					fOut.close();
					LOG.info(fileName +" success export excel ! And the excel had " + list.size() + " rows.");
				} catch (Exception e) {
					e.printStackTrace(System.err);
				}
			}
		}
	}
	
	private void excute() {
		try {
			List<MyObject> list = new ArrayList<MyObject>();
			StringBuilder content = null;
			StringBuilder str = new StringBuilder();
			StringBuilder str2 = new StringBuilder();
			MyObject o = new MyObject();
			o.setObj1("ORG_CODE");
			o.setObj2("ORG_NAME");
			o.setObj3("ORG_ADDRESS");
			o.setObj4("WAREHOUSE_ADDRESS");
			o.setObj5("LEGAL_PERSON");
			o.setObj6("COMPANY_PERSON");
			o.setObj7("QUALITY_PERSON");
			o.setObj8("ORG_TYPE");
			o.setObj9("ORG_LIMIT");
			o.setObj10("APPROVE_DATE");
			o.setObj11("VALID_DATE");
			o.setObj12("APPROVE_ORG");
			o.setObj13("MO_DESC");
			o.setObj14("MO_ID");
			list.add(o);
			for (int i = startNum; i <= endNum; i++) {
				content = readHtm1(filePath+i+".htm");
				Pattern pattern = Pattern.compile(regex);
				Matcher matcher = pattern.matcher(content);
				while (matcher.find()) {
					o = new MyObject();
					o.setObj1(matcher.group(1).trim().replace("<br>", ""));
					o.setObj2(matcher.group(2).trim().replace("<br>", ""));
					o.setObj3(matcher.group(3).trim().replace("<br>", ""));
					o.setObj4(matcher.group(4).trim());
					o.setObj5(matcher.group(5).trim().replace("<br>", ""));
					o.setObj6(matcher.group(6).trim().replace("<br>", ""));
					o.setObj7(matcher.group(7).trim().replace("<br>", ""));
					o.setObj8(matcher.group(8).trim());
					o.setObj9(matcher.group(9).trim());
					str.append(matcher.group(10).trim().replace(".", "-")//.replace("/", "-")
							.replace("、", "-").replace("．", "-").replace("－", "-")
							.replace("008-4-28变更","2008-4-28").replace("变更", "")
							.replace("2004年", "2004-01-01").replace("1004", "2004")
							.replace("年", "-").replace("月", "-").replace("日", ""));
					if (str.toString().equals("1")) str.delete(0, str.length());
					if (str.toString().equals("2006")) str.append("01-01");
					if (str.toString().endsWith("（新）")) {
						int index = str.toString().indexOf("-", 8);
						o.setObj10(str.toString().substring(0, index));
//						LOG.info(str.toString().substring(0, index));
					}
					if(str.toString().getBytes().length > str.length() && str.toString().getBytes().length != str.length()) {
						String str1 = UsualUtil.ToDBC(str.toString());
						str.delete(0, str.length());
						str.append(str1);
					}
					if (str.toString().endsWith("-")) {
						o.setObj10(str.toString().substring(0, str.length()-1));
//						LOG.info(str.toString().substring(0, str.length()-1));
					} else {
						 if(str.toString().indexOf("/") != -1) {
							 if (str.toString().indexOf("/") == 4) {
									o.setObj10(str.toString().replace("/", "-"));
								} else {
									o.setObj10(DateGroup.MMddYYtoStanderd(str.toString().replace("/", "-")));
								}
						 } else {
							 if (str.indexOf("-") == -1 && !str.toString().equals("") && UsualUtil.isNumeric(str.toString())) {
									if(str.length() < 6) {
										o.setObj10(ExlDate.translate(Double.valueOf(str.toString())));
									}
									else {
										SimpleDateFormat sdf1 = new SimpleDateFormat(DATE_FORMAT_1);
										SimpleDateFormat sdf2 = new SimpleDateFormat(DATE_FORMAT_2);
										java.util.Date date1 = sdf2.parse(str.toString());
										o.setObj10(sdf1.format(date1).toString());
									}
								} else if(str.toString().startsWith("0") || str.toString().startsWith("1")) {
									o.setObj10("20" + str.toString());
//									o.setObj11(DateGroup.MMddYYtoStanderd(str));
								} else {
									o.setObj10(str.toString());
								}
						 }
					}
					str.delete(0, str.length());
					
					str2.append(matcher.group(11).trim().replace(".", "-")//.replace("/", "-")
							.replace("、", "-").replace("２０１０-１-１８", "2010-1-18").replace("．", "-")
							.replace("2009年", "2009-01-01").replace("－", "-").replace("变更", ""));
					if (str2.toString().equals("1")) str2.delete(0, str2.length());

					if(str2.toString().getBytes().length > str2.length() && str2.toString().getBytes().length != str2.length()) {
						String str1 = UsualUtil.ToDBC(str2.toString());
						str2.delete(0, str2.length());
						str2.append(str1);
					}
					if (str2.toString().endsWith("-")) {
						o.setObj11(str2.toString().substring(0, str2.length()-1));
//						LOG.info(str2.toString().substring(0, str2.length()-1));
					} else {
						if (str2.toString().indexOf("/") != -1) {
							if (str2.toString().indexOf("/") == 4) {
								o.setObj11(str2.toString().replace("/", "-"));
							} else {
								o.setObj11(DateGroup.MMddYYtoStanderd(str2.toString().replace("/", "-")));
							}
						} else {
							if (str2.indexOf("-") == -1 && !str2.toString().equals("") && UsualUtil.isNumeric(str2.toString())) {
								if(str2.length() < 6) {
									o.setObj11(ExlDate.translate(Double.valueOf(str2.toString())));
								} else {
									SimpleDateFormat sdf1 = new SimpleDateFormat(DATE_FORMAT_1);
									SimpleDateFormat sdf2 = new SimpleDateFormat(DATE_FORMAT_2);
									java.util.Date date1 = sdf2.parse(str2.toString());
									o.setObj11(sdf1.format(date1).toString());
								}
							} else if(str2.toString().startsWith("0") || str2.toString().startsWith("1")) {
								o.setObj11("20" + str2.toString());
							} else {
								o.setObj11(str2.toString());
							}
						}
					}
					str2.delete(0, str2.length());
					
					o.setObj12(matcher.group(12).trim());
					o.setObj13(matcher.group(13).trim());
					o.setObj14(matcher.group(14).trim());
					
					
					list.add(o);
					LOG.info("file is " + i);
				}
			}
				writeExl(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		MedicalOrg instance = new MedicalOrg();
		instance.excute();
	}
}